package com.masterclient.app.modules.bridge;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselibrary.bean.pay.ThirdPayParam;
import com.eoner.baselibrary.utils.CookieNewUtil;
import com.eoner.baselibrary.utils.IntentUtil;
import com.eoner.baselibrary.utils.LoadCallBack;
import com.eoner.baselibrary.utils.UIUtils;
import com.eoner.baselibrary.utils.UtilCollection;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.baselibrary.widget.PermissionDialog;
import com.eoner.common.BuildConfig;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.Tools;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.managerlibrary.sobot.SobotManager;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.eoner.managerlibrary.user.UserDataManager;
import com.eoner.managerlibrary.weixin.WeiXinManager;
import com.eoner.middlelib.router.intercept.FCBaseIntercept;
import com.eoner.middlelib.router.map.FCRouterPath;
import com.masterclient.app.MainActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.CaptureActivity;
import com.masterclient.app.base.ConfirmDialog;
import com.masterclient.app.businessmodule.minemodule.point.PointActivity;
import com.masterclient.app.businessmodule.minemodule.point.PointProductsActivity;
import com.masterclient.app.businessmodule.usermodule.login.index.QuickLoginActivity;
import com.masterclient.app.businessmodule.usermodule.userinfo.UserInfoActivity;
import com.masterclient.app.modules.category.CategoryDetailActivity;
import com.masterclient.app.modules.chezhubang.CzbAuthorizeActivity;
import com.masterclient.app.modules.chezhubang.CzbWebActivity;
import com.masterclient.app.modules.coupon.CouponActivity;
import com.masterclient.app.modules.goods.beans.ShareProductBean;
import com.masterclient.app.modules.goods.newpage.activity.NewCommodityDetailActivity;
import com.masterclient.app.utils.CommonUtil;
import com.google.gson.Gson;
import com.masterclient.app.widget.ShareNewCommonDialog;
import com.sobot.chat.SobotApi;
import com.sobot.chat.api.enumtype.SobotChatTitleDisplayMode;
import com.sobot.chat.api.model.Information;
import com.sobot.chat.api.model.SobotLocationModel;
import com.sobot.chat.utils.StMapOpenHelper;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import wendu.dsbridge.CompletionHandler;
import wendu.dsbridge.OnReturnValue;

import static com.eoner.baselibrary.utils.Utils.bmpToByteArray;

public class JsApi {

    private BridgeActivity activity;
    private boolean isResume;
    private ConfirmDialog dialog;
    private RxPermissions rxPermissions;

    public JsBean getJsBean() {
        return jsBean;
    }

    public JsShareBean getShareBean() {
        return shareBean;
    }

    private JsBean jsBean;
    private JsShareBean shareBean;

    private String finishType = "";
    private String isShowDialog = "0";

    public String getFinishType() {
        return finishType;
    }

    public String getIsShowDialog() {
        return isShowDialog;
    }

    public void setIsShowDialog(String isShowDialog) {
        this.isShowDialog = isShowDialog;
    }

    public JsApi(BridgeActivity activity) {
        this.activity = activity;
        rxPermissions = new RxPermissions(activity);
        isResume = false;
    }

    public boolean isResume() {
        return isResume;
    }

    public void closeDilog() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @JavascriptInterface
    public void showActiveShare(Object share) {
        if (share == null && share.toString().length() > 3) return;
        activity.visibleRight();
        shareBean = new Gson().fromJson(share.toString(), JsShareBean.class);
    }


    @JavascriptInterface
    public void showCommonShare(Object share) {
        if (share == null && share.toString().length() > 3) return;
        shareBean = new Gson().fromJson(share.toString(), JsShareBean.class);
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (shareBean != null) {
                    activity.showShareDialog(shareBean);
                }
            }
        });
    }

    @JavascriptInterface
    public void shareGoods(Object share) {
        if (share == null && share.toString().length() > 3) return;
        ShareProductBean shareBean = new Gson().fromJson(share.toString(), ShareProductBean.class);
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (shareBean != null) {
                    activity.showGoodsShareDialog(shareBean);
                }
            }
        });
    }


    @JavascriptInterface
    public void shareWechat(Object img) {
        if (img == null) {
            return;
        }
        if (!Tools.isAppAvilible(activity, "com.tencent.mm")) {
            Toast.makeText(activity, "请先安装微信客户端", Toast.LENGTH_LONG).show();
            return;
        }
        try {
            JSONObject object = new JSONObject(img.toString());
            String imgStr = object.getString("img");
            if (!TextUtils.isEmpty(imgStr)) {
                shareWx(imgStr);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void shareWx(String imageUrl) {
        rxPermissions
                .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission.granted) {
                        String pathUri = null;
                        File path = UIUtils.saveImageToSdCard(activity, imageUrl);
                        if (WeiXinManager.checkVersionValid(activity) && WeiXinManager.checkAndroidNotBelowN()) {
                            pathUri = WeiXinManager.getFileUri(activity, path);
                        }
                        if (!TextUtils.isEmpty(pathUri)) {
                            wxSharePic("he" + System.currentTimeMillis(), path.getAbsolutePath());
                        } else {
                            Toast.makeText(activity, "保存失败", Toast.LENGTH_SHORT).show();
                        }
                    } else if (permission.shouldShowRequestPermissionRationale) {
                    } else {
                        Toast.makeText(activity, "保存文件权限申请失败,无法保存图片", Toast.LENGTH_SHORT).show();
                    }
                });
    }


    private void wxSharePic(String transaction, String path) {
        //初始化WXImageObject和WXMediaMessage对象
        WXImageObject imageObject;
        imageObject = new WXImageObject();
        imageObject.imagePath = path;
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imageObject;
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = transaction + Long.toString(System.currentTimeMillis());
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        IWXAPI api = WXAPIFactory.createWXAPI(activity, WeiXinManager.APP_ID);
        api.sendReq(req);
    }

    @JavascriptInterface
    public void saveImg(Object img) {
        if (img == null) {
            return;
        }
        try {
            JSONObject object = new JSONObject(img.toString());
            String imgStr = object.getString("img");
            rxPermissions
                    .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(permission -> { // will emit 2 Permission objects
                        if (permission.granted) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    File result = UIUtils.saveImageToSdCard(activity, imgStr);
                                    activity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (result != null) {
                                                Toast.makeText(activity, "保存成功", Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                                }
                            }).start();
                        } else if (permission.shouldShowRequestPermissionRationale) {
                        } else {
                            Toast.makeText(activity, "保存文件权限申请失败,无法保存图片", Toast.LENGTH_SHORT).show();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    //打开小程序
    @JavascriptInterface
    public void openMiniProgram(Object msg) {
        if (msg != null && msg.toString().length() > 3) {
            jsBean = new Gson().fromJson(msg.toString(), JsBean.class);
        }
        if (jsBean != null) {
            String appId = "wx8031a358899ba015\n"; // 填应用AppId
            IWXAPI api = WXAPIFactory.createWXAPI(activity, appId);

            WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
            req.userName = "gh_0d1a6e2f60fa"; // 填小程序原始id
            req.path = jsBean.getPath();                  ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
            req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
            api.sendReq(req);
        }
    }

    //分享小程序
    @JavascriptInterface
    public void openMiniShare(Object msg) {
        if (msg != null && msg.toString().length() > 3) {
            jsBean = new Gson().fromJson(msg.toString(), JsBean.class);
        }
        if (jsBean != null) {
            String url = jsBean.getUrl();
            String path = jsBean.getPath();
            String title = jsBean.getTitle();
            String mini_program_image = jsBean.getMini_program_image();
            String desc = jsBean.getDesc();
            String share_ticket = jsBean.getShare_ticket();

            WXMiniProgramObject miniProgram = new WXMiniProgramObject();
            miniProgram.webpageUrl = url;// 兼容低版本的网页链接
            if (share_ticket != null && share_ticket.equals("1")) {
                miniProgram.withShareTicket = true;
            }
            miniProgram.userName = "gh_0d1a6e2f60fa";// 小程序原始id
            miniProgram.path = path;//小程序页面路径
            if (BuildConfig.DEBUG) {
                if (BuildConfig.IS_EMULATION) {
                    miniProgram.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW;
                } else {
                    miniProgram.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_TEST;
                }

            } else {
                miniProgram.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;
            }
            WXMediaMessage mediaMessage = new WXMediaMessage(miniProgram);
            mediaMessage.title = title;//自定义
            mediaMessage.description = desc;//自定义
            shareBitMap(mini_program_image, mediaMessage);
        }
    }

    private void shareBitMap(final String url, WXMediaMessage mediaMessage) {
        if (!TextUtils.isEmpty(url)) {
            Utils.getBitmapResources(activity, url, new LoadCallBack<Bitmap>() {
                @Override
                public void loadSuccess(Bitmap mData) {
                    if (mData != null) {
                        mediaMessage.thumbData = bmpToByteArray(mData, false);// 小程序消息封面图片，小于128k
                        SendMessageToWX.Req req = new SendMessageToWX.Req();
                        req.message = mediaMessage;
                        req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前只支持会话
                        IWXAPI api = WXAPIFactory.createWXAPI(activity, "wx8031a358899ba015");
                        api.sendReq(req);
                    }
                }

                @Override
                public void loadFail() {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast toast = Toast.makeText(activity, "分享的图片失效", Toast.LENGTH_LONG);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                        }
                    });
                }
            });
        }
    }


    @JavascriptInterface
    public void share(Object msg) {
        if (msg != null && msg.toString().length() > 7) {
            jsBean = new Gson().fromJson(msg.toString(), JsBean.class);
        }
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (jsBean != null) {
                    activity.showShareDialog(jsBean);
                }
            }
        });
    }


    //添加线程管理并订阅
    private Disposable toSubscribe(Observable observable, Consumer next, Consumer error) {
        return observable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(next, error);
    }

//    @JavascriptInterface
//    public void removeBeforePage(Object msg) {
//        Activity activity =  UtilActivity.getBeforeActivity();
//        if (activity != null) {
//            activity.finish();
//        }
//    }

    @JavascriptInterface
    public void showShare(Object shareData) {
        if (shareData != null && shareData.toString().length() > 3) {
            activity.visibleRight();
            jsBean = new Gson().fromJson(shareData.toString(), JsBean.class);
        }
    }

    /**
     * 商品详情
     *
     * @param productId
     */
    @JavascriptInterface
    public void openGoodsDetail(Object productId) {
        isResume = false;
        Intent intent = new Intent(activity, NewCommodityDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("id", (String) productId);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @JavascriptInterface
    public void openProductDetail(Object product) {
        isResume = false;
        JsProductsBean productBean = new Gson().fromJson(product.toString(), JsProductsBean.class);
        Intent intent = new Intent(activity, NewCommodityDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("id", productBean.getProduct_id());
        bundle.putString("source_page", productBean.getS_product_sourcepage());
        bundle.putString("source_page_id", productBean.getS_product_sourcepage_id());
        bundle.putString("source_module", productBean.getS_product_sourcemodule());
        bundle.putString("source_position", productBean.getS_position());
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @JavascriptInterface
    public void openAward(Object type) {
        if (TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN))) {
            dialog = new ConfirmDialog(activity, "享受更多优惠，请您先去登录", "取消", "确定");
            dialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                @Override
                public void cancel() {
                    activity.finish();
                    dialog.dismiss();
                }

                @Override
                public void confirm() {
                    Intent intent = new Intent(activity, QuickLoginActivity.class);
                    intent.putExtra("intentSource", activity.title);
                    activity.startActivity(intent);
                    dialog.dismiss();
                }
            });
            dialog.setCanceledOnTouchOutside(false);
            dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        activity.finish();
                        return true;
                    } else {
                        return false;
                    }
                }
            });
            dialog.show();
        } else {
            isResume = false;
            JsBean jsBean = new Gson().fromJson(type.toString(), JsBean.class);
            switch (jsBean.getType()) {
                case "jifen":
                    activity.startActivity(new Intent(activity, PointActivity.class));
                    break;
                case "jiangjuan":
                    activity.startActivity(new Intent(activity, CouponActivity.class));
                    break;
                default:
            }
        }


    }

    /**
     * 首页相关
     *
     * @param position
     */
    @JavascriptInterface
    public void openMain(Object position) {
        isResume = false;
        Intent intent = new Intent(activity, MainActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("position", (String) position);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    /**
     * 品类详情页
     *
     * @param data
     */
    @JavascriptInterface
    public void openCategoryDetail(Object data) {
        isResume = false;
        if (data == null) return;
        JsCategoryDetailBean jsCategoryDetailBean = new Gson().fromJson(data.toString(), JsCategoryDetailBean.class);
        Intent intent = new Intent(activity, CategoryDetailActivity.class);
        intent.putExtra("type", jsCategoryDetailBean.type);
        intent.putExtra("cid", jsCategoryDetailBean.cid);
        intent.putExtra("brand_category_id", jsCategoryDetailBean.brandCategoryId);
        intent.putExtra("title", jsCategoryDetailBean.title);
        activity.startActivity(intent);
    }

    /**
     * 金币商城
     */
    @JavascriptInterface
    public void openPointProducts() {
        isResume = false;
        Intent intent = new Intent(activity, PointProductsActivity.class);
        activity.startActivity(intent);
    }

    /**
     * 店铺主页
     */
    @JavascriptInterface
    public void openShop(Object data) {
        isResume = false;
        if (data == null) return;
        JsShopBean jsShopBean = new Gson().fromJson(data.toString(), JsShopBean.class);
        if (TextUtils.isEmpty(jsShopBean.sellerId)) {
            ARouter.getInstance().build(AroutePath.STORE_ACTIVITY).withString("store_id", jsShopBean.brandId).navigation();
        }
        if (TextUtils.isEmpty(jsShopBean.brandId)) {
            ARouter.getInstance().build(AroutePath.STORE_ACTIVITY).withString("store_id", jsShopBean.sellerId).navigation();
        }
    }

    @JavascriptInterface
    public void goChoicenessStore(Object data) {
        isResume = false;
        if (data == null) return;
        JsShopBean jsShopBean = new Gson().fromJson(data.toString(), JsShopBean.class);
        ARouter.getInstance().build(AroutePath.STORE_ACTIVITY).withString("store_id",
                jsShopBean.sellerId).navigation();
    }

    @JavascriptInterface
    public String getInviteCode(Object msg) {
        return TextUtils.isEmpty(UserDataManager.getInstance().getInviteCode())
                ? "" : UserDataManager.getInstance().getInviteCode();
    }

    @JavascriptInterface
    public void contactCustomerService(Object msg) {
        Information info = SobotManager.getBaseInfo();
        //SobotApi.setChatTitleDisplayMode(activity, SobotChatTitleDisplayMode.ShowFixedText,"注销账户");
        SobotApi.setChatTitleDisplayMode(activity, SobotChatTitleDisplayMode.Default, "");
        SobotApi.startSobotChat(activity, info);
    }

    @JavascriptInterface
    public void czbAuthorize(Object data) {
        if (data.toString().length() < 3) return;
        try {
            JSONObject object = new JSONObject(data.toString());
            if ("0".equals(object.getString("sh_is_login"))) {
                isResume = true;
                Intent intent = new Intent(activity, QuickLoginActivity.class);
                intent.putExtra("intentSource", activity.title);
                activity.startActivity(intent);
                return;
            }
            if ("0".equals(object.getString("sh_car_owner_bind"))) {
                isResume = false;
                Intent intent = new Intent(activity, CzbAuthorizeActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("czb_procotol", object.getString("sh_auth_url"));
                intent.putExtras(bundle);
                activity.startActivityForResult(intent, 0x7);
            } else {
                isResume = false;
                Intent intent = new Intent(activity, CzbWebActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("url", object.getString("sh_car_owner_url"));
                intent.putExtras(bundle);
                activity.startActivity(intent);
                activity.finish();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void back(Object msg) {
        activity.finish();
    }

    @JavascriptInterface
    public void logOutAndGoHome(Object msg) {
        //TODO:清除用户信息
        UserDataManager.getInstance().clearLoginInfo();
//        Config.TOKEN = "";
//        Config.CUSTOMER_ID = "";
        activity.mPresenter.mRxManager.mRxBus.post(Config.LOGOUT_SUCCESS);
        Intent intent = new Intent(activity, MainActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("position", "0");
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @JavascriptInterface
    public void sendLogOffResultType(Object data) {
        Map<String, String> map = new Gson().fromJson(data.toString(), Map.class);
        finishType = map.get("resultType");
    }

    @JavascriptInterface
    public String checkNotificationAuthority(Object msg) {
        return UtilCollection.isNotificationEnabled(activity) + "";
    }

    @JavascriptInterface
    public void goNoticationAuthority(Object msg) {
        UtilCollection.requestNotify(activity);
        Config.task_notify = true;
    }

    @JavascriptInterface
    public void openWXApp(Object msg) {
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(activity, null);
        iwxapi.openWXApp();
    }

    @JavascriptInterface
    public void sendMessage(Object obj) {
        try {
            JSONObject object = new JSONObject(obj.toString());
            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + object.getString("mobile")));
            intent.putExtra("sms_body", object.getString("content"));
            activity.startActivity(intent);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //获取用户信息
    @JavascriptInterface
    public Object getUserInfo(Object msg) {
        Log.e(">>>>>>>>>>>>>", "===========");
        JSONObject user = new JSONObject();
        try {
            user.put("token", SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN));
            user.put("version", CookieNewUtil.getVersionName(Utils.getContext()));
            if (UserDataManager.getInstance().getUserCacheData() != null) {
                user.put("mobile", UserDataManager.getInstance().getMobile());
                user.put("userId", UserDataManager.getInstance().getCustomerId());
                user.put("level", UserDataManager.getInstance().getRoleLevel());
                user.put("nickName", UserDataManager.getInstance().getNickName());
                user.put("invite", UserDataManager.getInstance().getInviteCode());
                user.put("headUrl", UserDataManager.getInstance().getHeadImgUrl());
                user.put("realName", UserDataManager.getInstance().getIdCardRealName());
                user.put("idNumber", UserDataManager.getInstance().getIdCardNo());
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return user;
    }


    //上传头像
    @JavascriptInterface
    public void uploadUserProfilePhoto(Object msg) {
        String isUploadUserProfilePhoto = (String) msg;
        Intent intent = new Intent(activity, UserInfoActivity.class);
        if ("1".equals(isUploadUserProfilePhoto)) {
            intent.putExtra("user_type", "head");
        }
        activity.startActivity(intent);
    }

    //
    @JavascriptInterface
    public void setUpNickname(Object msg) {
        ARouter.getInstance().build(FCRouterPath.USER_MODIFY_NICK_NAME).navigation(activity, new FCBaseIntercept());
    }


    //取消登录
    @JavascriptInterface
    public void cancleLogin(Object msg) {

    }

    // 'target'  'targetID' 打开原生页面
    @JavascriptInterface
    public void openNativePage(Object msg) {
        try {
            JSONObject object = new JSONObject(msg.toString());
            String target = object.optString("target");
            String targetID = object.optString("targetID");
            CommonUtil.goAnyWhere(activity, target, targetID, "", "", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //  'navTitle'  'navIcon'  'target'  'targetID' 定制导航
    interface TitleListener {
        void set_title_item(String titleJson);
    }

    TitleListener titleListener;

    public TitleListener getTitleListener() {
        return titleListener;
    }

    public void setTitleListener(TitleListener titleListener) {
        this.titleListener = titleListener;
    }

    @JavascriptInterface
    public void removeCustomNavItem(Object msg) {
        activity.removeTitlebarRight();
    }

    @JavascriptInterface
    public void customNavItem(Object msg) {
        if (titleListener != null) {
            titleListener.set_title_item(msg.toString());
        }
    }


    //异步API
    @JavascriptInterface
    public void test(Object msg, CompletionHandler<String> handler) {


        System.out.println("msg ------ > " + msg);

        //handler.complete(msg+" [ asyn call]");
    }

//    @JavascriptInterface
//    public void test(String arg) {
//       System.out.println("just for testing ------- > " + arg);
//    }


    @JavascriptInterface
    public void callPayTransferPage(Object pay_param) {

//        String pay_order_no = "";
//        String channel = "";
//        String pay_amount = "";
//        String user_id = "";
//        String redirect_url = "";
//        String payback_url = "";
//        String time_expire = "";

        Gson gson = new Gson();

        ThirdPayParam thirdPayParam = gson.fromJson(pay_param.toString(), ThirdPayParam.class);

//        try {
//            JSONObject object = new JSONObject(pay_param.toString());
//            pay_order_no = object.getString("pay_order_no");
//            channel = object.getString("channel");
//            pay_amount = object.getString("pay_amount");
//            user_id = object.getString("user_id");
//            redirect_url = object.getString("redirect_url");
//            payback_url = object.getString("payback_url");
//            time_expire = object.getString("time_expire");
//
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }

        ARouter.getInstance().build(AroutePath.PAY_ACTIVITY).withString("pay_order_no", thirdPayParam.getPay_order_no())
                .withString("channel", thirdPayParam.getChannel())
                .withInt("pay_amount", Integer.valueOf(thirdPayParam.getPay_amount()).intValue())
                .withString("user_id", thirdPayParam.getUser_id())
                .withString("redirect_url", thirdPayParam.getRedirect_url())
                .withString("payback_url", thirdPayParam.getPayback_url())
                .withString("time_expire", thirdPayParam.getTime_expire())
                .navigation();
    }

    @JavascriptInterface//跳转到会员中心，滚动到商品列表
    public void goVipCenter(Object msg) {
        activity.finish();
        Intent intent = new Intent(activity, MainActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("position", "2");
        intent.putExtras(bundle);
        activity.startActivity(intent);
        activity.rxBus.post(Config.VIP_CENTER_SCROLL, "h5");
    }

    @JavascriptInterface
    public void updateTitle(Object title) {
        Log.e("======updateTitle", (String) title);
        activity.setTitle((String) title);
    }

    @JavascriptInterface
    public void pushConfirmOrderPage(Object msg) {
        try {
            JSONObject object = new JSONObject(msg.toString());
            String buy_product = object.optJSONObject("buy_product").toString();
            String buy_type = object.optString("buy_type");
            String charge_account = object.optString("charge_account");
            ARouter.getInstance().build(AroutePath.ORDER_SUBMIT_ACTIVITY).
                    withString("buy_type", buy_type).withString("buy_product", buy_product.toString()).withSerializable("charge_account", charge_account).navigation();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void getAddressBookMobile(Object data) {
        boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.READ_CONTACTS);
        if (!hasPermissions) {
            new PermissionDialog(activity, "开启通讯录权限", "获取通讯录权限以便更快捷的充值话费，请在下一个页面点击“允许”",
                    R.mipmap.icon_permission_contacts, this::requestPermissions).show();
        } else {
            Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            activity.startActivityForResult(intent, 0);
        }
    }

    private void requestPermissions() {
        rxPermissions
                .requestEach(Manifest.permission.READ_CONTACTS)
                .subscribe(permission -> {
                    if (permission.granted) {
                        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                        activity.startActivityForResult(intent, 0);
                    } else if (permission.shouldShowRequestPermissionRationale) {
                    } else {
                        Toast.makeText(activity, "访问通讯录权限申请失败,无法访问通讯录", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @JavascriptInterface
    public void changeTitleStyle(Object msg) {
        activity.changeTitleStyle((String) msg);
    }

    @JavascriptInterface
    public void changeNavigationBarColor(Object msg) {
        try {
            JSONObject object = new JSONObject(msg.toString());
            String alpha = object.optString("alpha");
            String color = object.optString("color");
            activity.changeNavigationBarColor(alpha, color);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void openFansMarketingShare(Object share) {
        JsNewShareBean shareBean = new Gson().fromJson(share.toString(), JsNewShareBean.class);
        activity.shareNew(shareBean);
    }

    public void gotoH5(String mobile) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("mobile", mobile);
            activity.dwebView.callHandler("getAddressBookMobile", new Object[]{jsonObject}, new OnReturnValue<String>() {
                @Override
                public void onValue(String retValue) {
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void changeBackIsShowDialogSwitch(Object msg) {
        isShowDialog = (String) msg;
    }

    @JavascriptInterface
    public void showNewInterceptorPop(Object msg) {
        activity.isInterceptBack = true;
    }

    @JavascriptInterface
    public void setIsInterceptDoubleClick(Object msg) {
        activity.isInterceptDoubleClick = (boolean) msg;
    }

    /**
     * 下載app
     */
    @JavascriptInterface
    public void openThirdApp(Object msg) {
        if (!CommonUtil.startApp(activity, "com.flowerbusiness.app")) {
            Uri uri = Uri.parse(SystemConfigStorage.getInstance().getB_android_apk_url());
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            activity.startActivity(intent);
        }
    }

    /**
     * 改變導航欄顔色
     */
    @JavascriptInterface
    public void setHeaderColor(String color) {
//        activity.changeNavigationBarColor("",color);
    }

    /**
     * 设置导航栏
     */
    @JavascriptInterface
    public void setNavibarHidden(Object msg) {
        try {
            JSONObject object = new JSONObject(msg.toString());
            int isHidden = object.optInt("isHidden");
            activity.setNavibarHidden(isHidden);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public String getToken(Object msg) {
        String token = SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN);
        if (TextUtils.isEmpty(token)) {
            //isResume = true;
        } else {
            isResume = false;
        }
        return token;
    }

    @JavascriptInterface
    public String scan(Object msg) {
        String token = SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN);
        if (TextUtils.isEmpty(token)) {
            token = "";
        }
        return token;
    }

    @JavascriptInterface
    public void openWeb(Object msg) {
        try {
            JSONObject object = new JSONObject(msg.toString());
            String target = object.optString("url");
            String targetID = object.optString("targetID");
            CommonUtil.goAnyWhere(activity, target, targetID, "", "", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void openMap(Object msg) {
        Map<String, String> map = new Gson().fromJson(msg.toString(), Map.class);
        if (activity.dialog != null) {
            activity.setDialog(map);
        }
    }

    @JavascriptInterface
    public void goLogin(Object msg) {
        Intent intent = new Intent(activity, QuickLoginActivity.class);
        intent.putExtra("intentSource", "");
        activity.getActivity().startActivity(intent);
    }

    @JavascriptInterface
    public void addNavShareButton(Object obj) {
        activity.visibleRight();
        this.obj = obj;
    }

    @JavascriptInterface
    public void deleteNavShareButton(Object msg) {
        activity.removeTitlebarRight();
    }

    Object obj;

    public void showDialog() {
        try {
            if (obj == null) {
                return;
            }
            JSONObject object = new JSONObject(obj.toString());
            String type = object.optString("type");
            if ("0".equals(type)) {
                String url = object.optString("url");
                String image = object.optString("image");
                String title = object.optString("title");
                String desc = object.optString("desc");
                ShareNewCommonDialog h5Dialog = new ShareNewCommonDialog(activity, true);
                h5Dialog.show();
                h5Dialog.setShareLinkData(url, title, desc, image);
            } else {
                String name = object.optString("name");
                String image = object.optString("image");
                String shareUrl = object.optString("share_url");
                String showMan = object.optString("show_man");
                String showPhone = object.optString("show_phone");
                String categoryName = object.optString("category_name");
                String iconUrl = object.optString("icon_url");
                ShareNewCommonDialog h5Dialog = new ShareNewCommonDialog(activity, false);
                h5Dialog.show();
                h5Dialog.setShareData(name, image, shareUrl, showMan, showPhone, categoryName, iconUrl);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void joinSuccess(Object msg) {
        Intent intent = new Intent(activity, MainActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("position", "1");
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    /**
     * 拨打电话
     */
    @JavascriptInterface
    public void callPhone(Object msg) {
        try {
            JSONObject object = new JSONObject(msg.toString());
            String phone = object.getString("phone");
            ConfirmDialog dialog = new ConfirmDialog(activity, "是否拨打电话", null, phone, "取消", "确定", "#FF6809");
            dialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                @Override
                public void cancel() {
                    dialog.dismiss();
                }

                @Override
                public void confirm() {
                    IntentUtil.toPhoneApp(activity, phone);
                    dialog.dismiss();
                }
            });
            dialog.show();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 扫码签到
     */
    String eventId = "";
    @JavascriptInterface
    public void scanCheckin(Object msg) {
        try {
            JSONObject object = new JSONObject(msg.toString());
            eventId = object.getString("event_id");
            rxPermissions = new RxPermissions(activity);
            boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.CAMERA);
            if (!hasPermissions) {
                new PermissionDialog(activity, "开启摄像头权限", "获取摄像头和相册权限以便扫码，请在下一个页面点击“允许”",
                        R.mipmap.icon_permission_phone, this::requestCameraPermissions).show();
            } else {
                Intent intent = new Intent(activity, CaptureActivity.class);
                intent.putExtra("eventId", eventId);
                try {
                    activity.startActivityForResult(intent, 111);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void requestCameraPermissions() {
        rxPermissions
                .requestEach(Manifest.permission.CAMERA)
                .subscribe(permission -> { // will emit 2 Permission objects
                    if (permission.granted) {
                        // `permission.name` is granted !
                        Intent intent = new Intent(activity, CaptureActivity.class);
                        intent.putExtra("eventId", eventId);
                        try {
                            activity.startActivityForResult(intent, 111);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // Denied permission without ask never again
                    } else {
                        // Denied permission with ask never again
                        // Need to go to the settings
                    }
                });
    }
}
